<template>
  <van-form @submit="onSubmit" @failed="onFail" class="form">
    <van-field
      v-model="form.username"
      name="username"
      left-icon="manager-o"
      clearable
      label="账号信息"
      placeholder="请输入者用户名"
      :rules="[{ required: true, message: '请输入者用户名' }]"
    />
    <van-field
      v-model="form.password"
      :type="type"
      clearable
      name="password"
      left-icon="guide-o"
      label="登录密码"
      placeholder="请输入登录密码"
      :right-icon="type == 'password' ? 'closed-eye' : 'eye-o'"
      :rules="[
        { required: true, message: '请输入登录密码' },
        {
          pattern: reg.pwd,
          message: '请输入6-16位数字和字符的组合密码',
        },
      ]"
      @click-right-icon="changeType"
    />
    <div style="margin: 16px" class="links">
      <p>
        <router-link class="color1" :to="{ name: 'zhuce' }"
          >没有账号,立即注册</router-link
        >
        >
      </p>
      <p>
        <router-link class="color2" :to="{ name: 'forgetpass' }"
          >忘记密码?</router-link
        >
      </p>
    </div>
    <div style="margin: 36px 16px">
      <van-button block type="info" native-type="submit">登录</van-button>
    </div>
  </van-form>
</template>


<script>
export default {
  data() {
    return {
      form: {},
      type: "password",
    };
  },
  mounted() {
    console.log(this.$route); // 注册成功带过来的参数
    if (this.$route.query.username) {
      this.form = {
        ...this.form,
        username: this.$route.query.username,
      };
    } else {
      if (localStorage.getItem("username")) {
        this.form = {
          ...this.form,
          username: localStorage.getItem("username"),
        };
      }
    }
  },
  methods: {
    changeType() {
      this.type = this.type == "password" ? "text" : "password";
    },
    onSubmit(value) {
      this.$ajax
        .findUser({
          password: value.password,
          username: value.username,
        })
        .then((res) => {
          if (res.length > 0) {
            this.$notify({ type: "success", message: "登录成功" });
            // this.$router.push({ name: "mine" });
            localStorage.setItem("username", value.username);
            // 存储用户信息 vuex
            this.changeUserInfo(res[0]);
          } else {
            this.ShowError("用户名或者密码不正确");
          }
        });
    },
    onFail() {
      this.$toast("请输入有效的登录信息");
    },
  },
};
</script>

<style lang="scss" scoped>
.form {
  margin-top: 20px;
  .links {
    display: flex;
    justify-content: space-between;
  }
  .color1 {
    color: rgb(247, 2, 2);
  }
  .color2 {
    color: rgb(247, 2, 2);
  }
}
</style>